<template>
  <!-- 导航 -->
  <el-row style="margin: 10px;background-color: ghostwhite;padding: 15px">
    <el-col :span="24">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item>任务管理</el-breadcrumb-item>
        <el-breadcrumb-item>任务列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
  </el-row>
  <!-- 搜索栏-->
  <el-row style="margin: 10px;background-color: ghostwhite;padding: 15px">
    <el-col :span="24">
      <el-form :model="taskQuery" inline>
        <el-form-item label="任务标题">
          <el-input v-model="taskQuery.taskTitle"/>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-select style="width: 100px" v-model="taskQuery.taskStatus">
            <el-option :value="0" label="全部"/>
            <el-option :value="1" label="正常"/>
            <el-option :value="2" label="暂停"/>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
              v-model="startTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
              v-model="endTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="loadTasks()" type="primary">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>

  <!-- 工具栏 -->
  <el-row style="margin: 0px 10px;background-color: ghostwhite;padding: 0px 10px">
    <el-col :span="24">
      <el-button-group>
        <el-button :disabled="curUserId!=project.userId" @click="toAddTask" type="primary">新增</el-button>
        <el-button :disabled="curUserId!=project.userId" @click="toEdits" type="primary">编辑</el-button>
        <el-button :disabled="curUserId!=project.userId" @click="toDeletes" type="primary">删除</el-button>
      </el-button-group>
    </el-col>
  </el-row>
  <!-- 数据列表 -->
  <el-row style="margin: 0px 10px;padding: 0px 15px">
    <el-col :span="24">
      <el-table :data="tasks" border stripe
                row-key="taskId"
                lazy
                :load="loadChildrenTask"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                ref="taskTable">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="taskId" label="#">
          <template #default="scope">
            <el-link @click="showDetail(scope.row.taskId)" type="success">
              {{ scope.row.taskId }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="taskTitle" label="任务标题"/>
        <el-table-column prop="user.username" label="负责人"/>
        <el-table-column label="任务工期" prop="taskDuration"/>
        <el-table-column prop="startTime" label="开始时间"/>
        <el-table-column prop="endTime" label="结束时间"/>
        <el-table-column prop="taskStatus" label="项目状态">
          <template #default="scope">
            <el-tag type="info" v-if="scope.row.taskStatus == 1">正常</el-tag>
            <el-tag type="primary" v-else-if="scope.row.taskStatus == 2">暂停</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column label="操作" width="330">
          <template #default="scope">
            <el-link @click="toAddSubTask(scope.row)" :disabled="curUserId!=project.userId" style="margin: 0px 5px"
                     type="primary">
              <el-icon>
                <Plus/>
              </el-icon>
              新增
            </el-link>
            <el-link @click="toEditTask(scope.row)" :disabled="curUserId!=project.userId" style="margin: 0px 5px" type="primary">
              <el-icon>
                <EditPen/>
              </el-icon>
              编辑
            </el-link>
            <el-link @click="toDeleteTask(scope.row)" :disabled="curUserId!=project.userId" style="margin: 0px 5px" type="primary">
              <el-icon>
                <Delete/>
              </el-icon>
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
  <!-- 新增弹窗组件 -->
  <taskAdd @addComplete="addTaskComplete" @cancelTaskAdd="cancelTaskAdd" :project="project" :is-show="addWinIsShow"
           :parent-task="parentTask"/>
  <!-- 任务详情组件 -->
  <task-detail @cancelTaskDetail="cancelTaskDetail" :project="taskDetails" :is-show="detailWinIsShow"/>
  <!-- 编辑任务的弹窗组件 -->
  <task-edit :project="project" :task-id="editTaskId" @cancel-task-edit="cancelTaskEdit" @edit-complete="editComplete"/>
</template>

<script setup>
import {onMounted, onBeforeMount, ref} from "vue";
import {useRouter, useRoute} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";
import projectRequest from "@/api/project.js";
import taskRequest from "@/api/task.js";
import {ArrowRight} from "@element-plus/icons-vue";
import taskAdd from "@/views/task/task-add.vue";
import taskDetail from "@/views/task/task-detail.vue"
import TaskEdit from "@/views/task/task-edit.vue";

// 封装搜索条件
let taskQuery = ref({});
// 封装查询的列表数据
let tasks = ref([]);
// 当前路由对象
let route = useRoute();
// 全局路由对象
let router = useRouter();
// 申明对象保存当前的项目对象
let project = ref({});// 不需要申明为响应式对象
// 当前用户编号
let curUserId = ref(-1);
let addWinIsShow = ref(false)
let parentTask = ref(null);
let detailWinIsShow = ref(false);
let taskDetails = ref({})
// 当前要编辑的任务的编号，默认是-1
let editTaskId = ref(-1);
//统计子任务数量
let subTasks=ref(0)
let taskTable=ref({})
/**
 * 工具栏新增按钮事件
 */
function toAddTask() {
  addWinIsShow.value = true;
}
/**
 * 工具栏删除按钮
 */
function toDeletes(){
  let selectedRows = taskTable.value.getSelectionRows();
  if (selectedRows.length == 0) {
    ElMessage({
      type: "warning",
      message: "你没有选中任何数据"
    });
    return;
  }
  ElMessageBox.confirm(
      '您确定要删除选中的项目吗？',
      'Warning',
      {
        confirmButtonText: '是的',
        cancelButtonText: '点错了',
        type: 'warning',
      }
  ).then(() => {
    let taskIds = [];
    selectedRows.forEach(row => {
      taskIds.push(row.taskId);
    })
    taskRequest.deleteTasks(taskIds, res => {
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "成功删除[" + res.data + "]条数据"
        })
        loadTasks();
      } else {
        ElMessage({
          type: "warning",
          message: "删除失败"
        })
      }
    });
  }).catch(() => {
  });
}
/**
 * 工具栏编辑按钮
 */
function toEdits() {
  let selectedRows = taskTable.value.getSelectionRows();
  if (selectedRows.length > 1) {
    ElMessage({
      type: "warning",
      message: "编辑只能编辑一条数据"
    });
  } else if (selectedRows.length == 0) {
    ElMessage({
      type: "warning",
      message: "你没有选中任何数据"
    });
  } else if (selectedRows[0].userId == curUserId || project.value.userId == curUserId) {
    toEditTask(selectedRows[0]);
  } else {
    ElMessage({
      type: "warning",
      message: "你只能编辑你自己负责的任务"
    });
  }
}
/**
 * 行删除按钮
 * @param task
 */
function toDeleteTask(task) {
  taskRequest.countSubTasks(task.taskId,res=>{
    subTasks.value=res.code;
    // console.log("subTasks的值为:"+subTasks)
    // console.log("subTasks.value的值为"+subTasks.value)
  })
  if ( subTasks.value == 0) {
    // subTasks.value=0;
    ElMessageBox.confirm(
        '您确定要将项目[' + task.taskTitle + "]删除吗？",
        'Warning',
        {
          confirmButtonText: '是的',
          cancelButtonText: '点错了',
          type: 'warning',
        }
    ).then(() => {
      taskRequest.deleteTask(task.taskId, res => {
        ElMessage({
          type: "success",
          message: "操作完成"
        });
        loadTasks();
      })
    }).catch(() => {
    });
  }
  else {
    ElMessage({
      type:"warning",
      message:"请先删除该项目的子项目"
    })
  }
}
/**
 * 行级新增任务事件
 * @param task
 */
function toAddSubTask(task) {
  console.log(task)
  parentTask.value = task;
  addWinIsShow.value = true;
}
/**
 * 行级编辑按钮事件
 * @param task
 */
function toEditTask(task){
  editTaskId.value = task.taskId;
}
/**
 * 编辑完成的事件
 */
function editComplete(){
  // 更新数据表
  cancelTaskEdit();
}

/**
 * 编辑取消的事件
 */
function cancelTaskEdit(){
  // 将editTaskId修改为-1
  editTaskId.value = -1;
}
/**
 * 任务详情
 * @param task
 */
function showDetail(taskId) {

  detailWinIsShow.value = true;

taskRequest.selectTaskDetailsByTaskId(taskId,res=>{
  taskDetails.value=res.data;

})
}

/**
 * 加载子任务列表
 * @param task 当前这一行数据对象
 * @param node  树节点
 * @resole 函数，用来将我们的数据加入到列表中
 */
function loadChildrenTask(task, node, resole) {
  // 加载数据
  taskRequest.loadTaskByProjectId(project.value.projectId, task.taskId, res => {
    // 调用resole函数将查询的结果加入列表
    resole(res.data);
  })
}

/**
 * 加载任务列表
 * @param parentId 父任务编号
 */
function loadTasks(parentId) {
  // 通过API加载任务列表
  taskRequest.loadTaskByProjectId(project.value.projectId, parentId, res => {
    tasks.value = res.data;
  })
}

/**
 * 加载当前的项目对象
 * @param projectId
 */
function loadProject(projectId) {
  projectRequest.getProjectById(projectId, res => {
    project.value = res.data;
    // 默认加载一级任务
    loadTasks(0);
  })
};

/**
 * 加载当前的任务对象
 * @param taskId
 */
function loadCurTask(task) {
  projectRequest.getProjectById(task.value, res => {
    project.value = res.data;
    // 默认加载一级任务
    loadTasks(0);
  })
};
onBeforeMount(() => {
  // 获取路由中的参数
  let projectId = route.params.projectId
  if (projectId) {
    // 加载项目对象
    loadProject(projectId);
  } else {
    ElMessage({
      type: "info",
      message: "请检查您的网络!"
    })
    router.push("/home");
  }
  // 获取用户编号
  curUserId = localStorage.getItem("userId");
  console.log(curUserId);

})
</script>

<style scoped>

</style>